package com.softcits.email.auth;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.softcits.email.model.LoginUser;
import com.softcits.email.utils.BlankUtil;
import com.softcits.email.utils.ResponseUtil;
import com.softcits.email.utils.ResultUtil;
import com.softcits.email.utils.SpringUtils;

public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
 
    private AuthenticationManager authenticationManager;
    
    public JwtLoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
    
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        try {
            LoginUser user = JSONObject.parseObject(request.getInputStream(), LoginUser.class);
            checkLoginForm(user, response);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(JSON.toJSONString(user), user.getUserPassword(), new ArrayList<>()));
        } catch (IOException e) {
            ResponseUtil.write(response, ResultUtil.error("数据读取错误"));
        }

        return null;
    }
    
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException failed) throws IOException, ServletException {
        ResponseUtil.write(response, ResultUtil.error(failed.getMessage()));
    }
    
    
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
            FilterChain chain, Authentication authResult) throws IOException, ServletException {
        SoftCitsUser user = (SoftCitsUser) authResult.getPrincipal();
        if(jwtTokenUtil == null) {
            jwtTokenUtil = (JwtTokenUtil) SpringUtils.getBean("jwtTokenUtil");
        }
        user.setUserLastLoginTime(String.valueOf(System.currentTimeMillis()));
        String token = jwtTokenUtil.createToken(user);
        user.setToken(jwtTokenUtil.getTokenPrefix() + token);
        response.addHeader(jwtTokenUtil.getTokenHeader(), jwtTokenUtil.getTokenPrefix() + token);
        ResponseUtil.write(response, ResultUtil.success(user));
    }
    
    /**
     * 校验参数
     *
     * @param loginForm
     */
    private void checkLoginForm(LoginUser user, HttpServletResponse response) {
        if (BlankUtil.isBlank(user.getLoginName())) {
            ResponseUtil.write(response, ResultUtil.error("Login Name can not be empty."));
            return;
        }
        if (BlankUtil.isBlank(user.getUserPassword())) {
            ResponseUtil.write(response, ResultUtil.error("Password can not be empty."));
            return;
        }
    }
}
